using System;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using IdentityModel.Client;
using Newtonsoft.Json.Linq;

namespace ConsoleClient02
{
    class Program
    {

        public static void Main(string[] args) => MainAsync().GetAwaiter().GetResult();

        private static async Task MainAsync()
        {
            // discover endpoints from metadata
            //var client = new HttpClient();
            var client = new HttpClient(new HttpClientHandler
            {
                UseProxy = true,    // 使用代理，
                Proxy = new WebProxy(new Uri("http://localhost:8888"))      // port:8888就是Fiddler默认监听的端口
            });

            var id4Url = "http://localhost:5000";
            var disco = await client.GetDiscoveryDocumentAsync(id4Url);
            if (disco.IsError)
            {
                Console.WriteLine(disco.Error);
                return;
            }

            // request token
            var tokenResponse = await client.RequestPasswordTokenAsync(new PasswordTokenRequest
            {
                Address = disco.TokenEndpoint,
                ClientId = "password_client",
                ClientSecret = "password_client",
                UserName = "root",
                Password = "root",
                Scope = "api1 email offline_access"
            });


            if (tokenResponse.IsError)
            {
                Console.WriteLine(tokenResponse.Error);
                return;
            }
            else
            {
                Console.WriteLine(tokenResponse.Json);
                Console.WriteLine("\n\n");
            }


            {
                // call api
                var apiClient = new HttpClient();
                apiClient.SetBearerToken(tokenResponse.AccessToken);

                var response = await apiClient.GetAsync("http://localhost:5001/identity/get");
                if (!response.IsSuccessStatusCode)
                {
                    Console.WriteLine(response.StatusCode);
                }
                else
                {
                    var content = response.Content.ReadAsStringAsync().Result;
                    Console.WriteLine(JArray.Parse(content));
                }
            }

            {
                //换取新token
                Console.WriteLine("换取新token");
                Console.WriteLine("现有token的信息: "+tokenResponse.Json);
                tokenResponse = await client.RequestRefreshTokenAsync(new RefreshTokenRequest
                {
                    Address = disco.TokenEndpoint,
                    ClientId = "password_client",
                    ClientSecret = "password_client",
                    RefreshToken = tokenResponse.RefreshToken
                });

                if (tokenResponse.IsError)
                {
                    throw new Exception(tokenResponse.Error);
                }
               
                Console.WriteLine("换取token的信息: "+tokenResponse.Json);
            }
             
           
        }
    }
}
